package com.wngbms;

import com.google.common.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Nullable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;

@Slf4j
public class GuavaAsync {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        ListeningExecutorService gPool = MoreExecutors.listeningDecorator(pool);

        FutureCallback<Object> callback = new FutureCallback<Object>() {
            @Override
            public void onSuccess(@Nullable Object o) {
                log.info("success {}", o);
            }

            @Override
            public void onFailure(Throwable throwable) {
                log.error("failed", throwable);
            }
        };

        // ------------------------------------------------------------------------------------------

        ListenableFuture<?> future = gPool.submit(() -> {
            log.info("do task");
//            parkS(3L);
        });

        /**
         * 回调函数是在主线程执行
         */
//        Futures.addCallback(future, callback);

        /**
         * 回调方法是线程池线程执行,
         * 回调方法执行的线程 与 执行任务的线程不是同一个线程
         */
        Futures.addCallback(future, callback, gPool);

        // ------------------------------------------------------------------------------------------

        /**
         * 待返回值的任务 Callable
         */
        future = gPool.submit(() -> {
            log.info("do task2");
            return "resp";
        });

        Futures.addCallback(future, callback, gPool);

        log.info("main end");

//        gPool.shutdown();
    }

    // ns us ms s
    public static void parkMs(long l) {
        LockSupport.parkNanos(l * 1000L * 1000L);
    }

    public static void parkS(long l) {
        parkMs(l * 1000L);
    }

}
